package com.health.mapp.service;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URLDecoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
 





















import com.health.db.dao.ServiceInterface;
import com.health.db.model.IHisIMMessage;
import com.health.db.model.IMsgIMMessage;
import com.health.db.service.msg.IIHisIMMessageService;
import com.health.db.service.msg.IIMsgIMMessageService;
 
import com.health.mapp.bean.rongcloud.Content;
import com.health.mapp.bean.rongcloud.RongCloudCallBackReq;
import com.health.mapp.bean.rongcloud.RongCloudCallBackResp;
import com.health.mapp.bean.rongcloud.RongCloudHelper;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.Response;
import com.health.redis.RedisClient;
import com.health.redis.RedisOperatiorLogic;

/**
 * Servlet implementation class RongCloudCallBack
 */
public class RongCloudCallBack extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(RongCloudCallBack.class);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RongCloudCallBack() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String result =null;

		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");

		PrintWriter out = response.getWriter();
		out.println(out.toString());
		//out.println("\r\n");
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		long s = System.currentTimeMillis();
		//doGet(request, response);
		//POST /receive_message.php?timestamp=1408706337&nonce=14314&signature=45beb7cc7307889a8e711219a47b7cf6a5b000e8 HTTP/1.1
		//		Host: demo.com.cn

		//		fromUserId=123&toUserId=456&objectName=RC%3ATxtMsg&content=%7B"content"%3A"hello"%7D&timestamp=1408710653491&channelType=PERSON&msgTimestamp=1408710653491&msgUID=596E-P5PG-4FS2-7OJK
		//RongCloudCallBack request:channelType=GROUP&fromUserId=69&toUserId=28326&msgTimestamp=1494407751008&timestamp=1494407751008&objectName=RC:TxtMsg&content={"content":"我的人都有一个人","user":{"name":"首儿健康","icon":"http:\/\/shouer.oss-cn-beijing.aliyuncs.com\/docImage\/kefu.png","id":"69"}}&msgUID=5DV3-955C-0C1D-LKDH
		ServletContext servletContext = request.getSession()				.getServletContext();
		 ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);  

		//RedisOperatiorLogic   redisOperatiorLogic=(RedisOperatiorLogic) applicationContext.getBean("redisOperatiorLogic");
		IIMsgIMMessageService   iMsgIMMessageService=(IIMsgIMMessageService) applicationContext.getBean("iMsgIMMessageService");

		
		String fromUserId= null;      //		发送用户 Id。
		String toUserId	= null;      //	接收用户 Id，即为客户端 targetId。
		String objectName= null	;  //	消息类型，文本消息 RC:TxtMsg 、 图片消息 RC:ImgMsg 、语音消息 RC:VcMsg 、图文消息 RC:ImgTextMsg 、位置消息 RC:LBSMsg 、添加联系人消息 RC:ContactNtf 、提示条通知消息 RC:InfoNtf 、资料通知消息 RC:ProfileNtf 、通用命令通知消息 RC:CmdNtf 、客服握手消息 RC:HsMsg 、客服挂断消息 RC:SpMsg，详细请参见消息类型说明文档。
		String content = null;        //		发送消息内容。
		String timestamp= null;      //		服务端收到客户端发送消息时的服务器时间（1970年到现在的毫秒数）。
		String channelType	= null;  //	会话类型，二人会话是 PERSON 、讨论组会话是 PERSONS 、群组会话是 GROUP 、聊天室会话是 TEMPGROUP 、客服会话是 CUSTOMERSERVICE 、 系统通知是 NOTIFY 、应用公众服务是 MC 、公众服务是 MP。
		                             //客户端 SDK 中为 ConversationType ，二人会话是 1 、讨论组会话是 2 、群组会话是 3 、聊天室会话是 4 、客服会话是 5 、 系统通知是 6 、应用公众服务是 7 、公众服务是 8。
		String msgTimestamp	= null;  //	timestamp 的别名，主要为兼容一些开发框架使用（1970年到现在的毫秒数）。
		String msgUID= null	;     //	可通过 msgUID 确定消息唯一。
		
		
		

		// TODO Auto-generated method stub
		
		
		
		request.setCharacterEncoding("UTF-8");  
		InputStream is = null;
		  
		 
		 
		String failResult="";
		String allXml="";
		try {
			is = request.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line).append("\n");
			}
			br.close();
			is.close();

			allXml = URLDecoder.decode(sb.toString().trim(),"utf-8");
			//allXml =  sb.toString().trim();
			if(allXml.startsWith("="))
			{
				allXml=allXml.substring(1);
			}
			 

			
			// 解释报文
			// 1、采用正则表达式分析
			/*String regex = "<inXML>(.*)</inXML>";
			RE re = new RE(regex);
			re.match(requestContent);
			String inXml = re.getParen(1);*/
			if(allXml==null || "".equals(allXml)){
				throw new Exception("ERROR-001: 请求报文为空！");
			}
			
			
			 
			
			logger.debug("RongCloudCallBack request:"+allXml);
			
			
			
		
	    
			
		IMsgIMMessage message =null;	 
		//先进先出队列
		String key="queen_imsg_im_message";
		String result=null;
		 
		try
		{
			
			RedisClient.lpushDataToRedis(key, allXml);
			//String s1d=(String) RedisClient.rpopDataOutRedis(key);
			//logger.debug("s1d"+s1d);
			long a = System.currentTimeMillis();
			logger.debug("RedisClient cost:"+(a-s)+"ms insert one record");
		}
		catch(Exception e)
		{
			//e.printStackTrace();
			message= RongCloudHelper.parseObject(allXml);
			logger.debug(e.getCause()); 
		//	System.out.println("message:"+message);
			
	 
			iMsgIMMessageService.insert(message);
			long b = System.currentTimeMillis();
			logger.debug("iMsgIMMessageService cost:"+(b-s)+"ms insert one record");
		}
		
			
		RongCloudCallBackResp resp= new RongCloudCallBackResp();
			
			
		resp.setResult(result);
			
		String resultJson = genJsonResp(resp);
		
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(resultJson);
		out.println("\r\n");
		out.flush();
		out.close();
		logger.debug("RongCloudCallBack response:"+resultJson);
		} catch (Exception e) {
			e.printStackTrace();
			// TODO Auto-generated catch block
			 logger.warn(e.getCause());
		}
	}
	
	
	/**
	 * @param resp
	 * @return
	 */
	public static String genJsonResp(Response o) {
		String result = null;
		ObjectMapper objectMapper = new ObjectMapper();
		//版本2.x
         //		Jackson 序列化 如何让为NULL的属性不参与序列化
		objectMapper.setSerializationInclusion(Inclusion.NON_NULL); 
		JsonGenerator jsonGenerator = null;
		ByteArrayOutputStream out = null;
		try {
			out = new ByteArrayOutputStream();

			//
			jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
					out, JsonEncoding.UTF8);
			jsonGenerator.writeObject(o);
			result = out.toString("UTF-8");
			out.flush();
			out.close();
		} catch (IOException e1) {
			 logger.warn(e1.getCause());
			result = "{\"errorCode\":100,\"errorMsg\":\"System error.\"}";
		}
		return result;
	}
}
